<template>
  <el-dialog :visible.sync="currentVisible"
             append-to-body
             destroy-on-close
             :close-on-click-modal="false"
             :title="$t('custom.bots.psa.title')"
             custom-class="progress-status-modal"
             width="500px">

    <div class="progress-status-modal-content relative"
         v-loading="loading">
      <template v-if="!form.psa && !loading">
        <div class="absolute w-full h-full center-center progress-status-modal-content-mask">
        </div>
        <div class="absolute w-full h-full  center-center progress-status-modal-content-get">
          <el-button size="mini"
                     @click="goGetStart"
                     type="primary">{{ $t('custom.bots.psa.toGetStartedBtn') }}</el-button>
        </div>
      </template>

      <el-form :model="form"
               ref="form"
               label-position="right"
               label-width="140px"
               :rules="rules">
        <el-form-item :label="$t('custom.bots.psa.labelPSA')">
          <el-select :disabled="true"
                     v-model="form.psa"
                     style="width:100%"
                     :placeholder="$t('custom.bots.psa.noData')">
            <el-option v-for="item in psas"
                       :key="item.dictValue"
                       :label="item.dictLabel"
                       :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('custom.bots.psa.labelStatus')">
          <el-select multiple
                     collapse-tags
                     v-model="form.status"
                     clearable
                     style="width:100%"
                     :placeholder="$t('custom.bots.psa.noData')">
            <el-option v-for="(item,index) in statuses"
                       :key="index"
                       :label="item"
                       :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div class="z-modal-footer">
        <el-button type="primary"
                   size="small"
                   @click="onConfirm">{{ $t('custom.bots.psa.save') }}</el-button>
        <el-button size="small"
                   @click="onCancel">{{ $t('custom.bots.psa.cancel')  }}</el-button>
      </div>
    </div>

  </el-dialog>
</template>

<script>
import { useDicts, } from '@/components/storybook/hooks/useDict'
import { fetchTicketStatus, fetchSoftwareSetting, updateSoftwareSetting } from '@/api/new'
import useErrorMessage from '@/components/storybook/hooks/useErrorMessage'
import { get } from 'lodash'

export default {
  name: 'ProgressStatusModal',
  props: {
    visible: Boolean,
  },
  data () {
    return {
      loading: false,
      form: {
        psa: undefined,
        status: []
      },
      rules: {},
      softwareSetting: {},
      statuses: []
    }
  },
  computed: {
    currentVisible: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    },
    psas () {
      return useDicts('get_started_about_psa')
    }
  },
  created () {
    this.init()
  },
  methods: {
    async init () {
      try {
        this.loading = true
        const softwareSetting = await this.getSoftwareSetting()

        this.softwareSetting = softwareSetting

        const selectedPSACode = get(softwareSetting, 'software.selectedPSA') || []

        if (selectedPSACode.length > 0) {
          this.form.psa = selectedPSACode[0]

          const selectedPSA = useDicts('integration_list').find(i => i.dictLabel === 'name' && i.dictValue === this.form.psa)

          if (selectedPSA) {
            const subjectCode = selectedPSA.subjectCode
            this.statuses = await this.getTicketStatus(subjectCode)

            const ticketStatus = get(softwareSetting, 'softwareSetting.selectedPSA').find(i => i.key === 'ticketStatus')

            if (ticketStatus) {
              this.form.status = (ticketStatus.value || '').split(',')
              this.form.id = ticketStatus.id
            }
          }
        }
      } catch (error) {
        useErrorMessage(error)
      } finally {
        this.loading = false

      }
    },
    onCancel () {
      this.currentVisible = false
      this.$emit('cancel')
    },
    async onConfirm () {
      try {
        this.loading = true
        const { status, id } = this.form
        const params = [{
          id,
          key: "ticketStatus",
          softwareName: "selectedPSA",
          value: status.join()
        }]
        const { data: response } = await updateSoftwareSetting(params)
        if (response.code !== 0) {
          throw response.msg
        }

        this.$message.success(response.msg)
        this.currentVisible = false
        this.$emit('success', response.data || {})
      } catch (error) {
        useErrorMessage(error)
      } finally {
        this.loading = false
      }
    },
    async getTicketStatus (subjectCode) {
      const params = {
        subjectCode
      }
      const { data: response } = await fetchTicketStatus(params)
      if (response.code !== 0) {
        throw response.msg
      }

      return response.data || []
    },
    async getSoftwareSetting () {
      const { data: response } = await fetchSoftwareSetting()
      if (response.code !== 0) {
        throw response.msg
      }

      return response.data || {}
    },
    goGetStart () {
      this.$store.state.GetStarted.dialogStatus = false
      setTimeout(() => {
        this.currentVisible = false
        this.$store.state.GetStarted.dialogStatus = true
      }, 0)
    }
  }
}
</script>

<style lang="scss" scoped>
.progress-status-modal {
  &-content {
    &-mask {
      opacity: 0.8;
      background: #ededed;
      z-index: 998;
    }
    &-get {
      z-index: 999;
    }
  }
}
</style>